package com.xlx.openLink.snmp.tk;

import com.xlx.openLink.base.SnmpException;
import lombok.extern.slf4j.Slf4j;
import net.percederberg.mibble.Mib;
import net.percederberg.mibble.MibLoader;
import net.percederberg.mibble.MibValueSymbol;
import net.percederberg.mibble.value.ObjectIdentifierValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * mib文件解析
 */
@Component
@Slf4j
public class AnalyzeMib {

    @Autowired
    private MibLoader mibLoader;
    /**
     * 根据 oid  mib对象
     *
     * @param oid
     * @return
     * @throws SnmpException
     */
    public MibValueSymbol getMibSymbolByOid(String oid) throws SnmpException {
        if (oid.startsWith(".")) {
            oid = oid.replaceFirst(".", "");
        }
        Mib[] mibs = mibLoader.getAllMibs();
        MibValueSymbol mibValueSymbol = null;
        for (int i = 0; i < mibs.length; ++i) {
            mibValueSymbol = mibs[i].getSymbolByValue(oid);
            if (mibValueSymbol != null) {
                break;
            }
        }
        if (mibValueSymbol == null) {
            throw new SnmpException("未找到节点");
        } else {
            return mibValueSymbol;
        }
    }

    /**
     * 根据 oid  mib对象
     *
     * @param oid
     * @return
     * @throws SnmpException
     */
    public MibValueSymbol locateSymbolByOid(String oid){
        if (oid.startsWith(".")) {
            oid = oid.replaceFirst(".", "");
        }
        ObjectIdentifierValue iso = mibLoader.getRootOid();
        ObjectIdentifierValue match = iso.find(oid);
        if(match==null){
            log.error("oid:"+oid+"未找到该oid的节点");
            return null;
        }else {
            return match.getSymbol();
        }

    }
}
